import pygame,sys,os,eztext
from pygame.locals import *
cardSprites = None
deck = None
textY = None
def screenSetup():
    global backgroundSurface
    global screen
    backgroundFileName = os.path.join("data","menuBackground.png") 
    backgroundSurface = pygame.image.load(backgroundFileName)
    screen.blit(backgroundSurface,(0,0))
    pygame.display.flip()


def load_image(name,colorkey):
    fullname = os.path.join("data", name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print "Cannot load image:", name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image


def saveDeck(name):
    fileName = os.path.join("decks",name+".deck")
    f = open(fileName,'w')
    for a in deck:
        fileLine = a + "\n"
        f.write(fileLine)
    f.write("end")
    f.close()
    
def renderCards():
    WorkerCard()
    MacemanCard()
    WarriorCard()
    BruteCard()
    ShockSpell()
    
def renderInterface():
    ResetButton()
    SaveButton()
    ExitButton()
def run(theScreen):
    global cardSprites
    global textSprites
    global inputSprites
    global messageSprites
    global buttonSprites
    global deck
    global screen
    global textY
    global selected
    global end
    screen = theScreen
    textY = 40
    selected = None
    cardSprites = pygame.sprite.Group()
    textSprites = pygame.sprite.Group()
    messageSprites = pygame.sprite.Group()
    inputSprites = pygame.sprite.Group()
    buttonSprites = pygame.sprite.Group()
    deck = []
    screenSetup()
    renderCards()
    renderInterface()
    end = False
    
    
    clock = pygame.time.Clock()
    while end == False:
        clock.tick(60)
        events = pygame.event.get()
        for event in events:
             
            if event.type == QUIT:
                
                sys.exit(0)
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                hitCard = False
                hitButton = False
                for card in cardSprites:
                    hitMob = card.rect.collidepoint(pos)
                    if hitMob == 1:
                        card.select()
                        hitCard = True
                if hitCard == False:
                    for button in buttonSprites:
                        hitSprite = button.rect.collidepoint(pos)
                        if hitSprite == 1:
                            button.function()
                            hitButton = True
                        if hitButton==False and selected != None:
                   
                            selected.unselect()
        buttonSprites.update(events)
        cardSprites.update(events)
        messageSprites.update()
        buttonSprites.draw(screen)
        cardSprites.draw(screen)
        textSprites.draw(screen)
        messageSprites.draw(screen)
        events = []
        pygame.display.flip()
    screen.blit(backgroundSurface,(0,0))
class Card(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        cardSprites.add(self)
        self.num = 0
        self.selected = False
    def update(self,events):
        if self.selected == True:
            for event in events:
                if event.type == KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        try:
                            for txtbox in inputSprites:
                                amount = int(txtbox.value)
                                self.num = amount
                                self.add()
                                inputSprites.empty()
                        except ValueError:
                            Error("You must input a number, then hit Enter")
            inputSprites.update(events)
            inputSprites.clear(screen,backgroundSurface)
            inputSprites.draw(screen)
    def select(self):
        global selected
        if selected != None:
            selected.unselect()
        txtLocX = self.rect.bottomleft[0]
        txtLocY = self.rect.bottomleft[1] + 10
        txtbox = eztext.Input(x=txtLocX,y=txtLocY,color=(0,0,0),prompt=("how many?: "))
        inputSprites.add(txtbox)
        inputSprites.draw(screen)
        self.selected = True
        selected = self
    def unselect(self):
        global selected
        selected = None
        inputSprites.clear(screen,backgroundSurface)
        self.selected = False
        for sprite in inputSprites:
            sprite.kill()
    def add(self):
        global textY
        for a in range(self.num):
            deck.append(self.name)
        Text(str(self.num) + " " +self.name,textY)
        textY += 30
class WorkerCard(Card):
    def __init__(self):
        Card.__init__(self)
        self.image = load_image("workerCard.png",-1)
        self.name = "Worker"
        self.rect = self.image.get_rect()
        self.rect.topleft = (55,55)
class WarriorCard(Card):
    def __init__(self):
        Card.__init__(self)
        self.image = load_image("warriorCard.png",-1)
        self.name = "Warrior"
        self.rect = self.image.get_rect()
        self.rect.topleft = (205,55)
class MacemanCard(Card):
    def __init__(self):
        Card.__init__(self)
        self.image = load_image("macemanCard.png",-1)
        self.name = "Maceman"
        self.rect = self.image.get_rect()
        self.rect.topleft = (355,55)
class BruteCard(Card):
    def __init__(self):
        Card.__init__(self)
        self.image = load_image("bruteCard.png",-1)
        self.name = "Brute"
        self.rect = self.image.get_rect()
        self.rect.topleft = (505,55)
class ShockSpell(Card):
    def __init__(self):
        Card.__init__(self)
        self.image = load_image("bruteCard.png",-1)
        self.name = "Shock"
        self.rect = self.image.get_rect()
        self.rect.topleft = (55,255)
        
class Text(pygame.sprite.Sprite):
    def __init__(self,name,y):
        global textSprites
        pygame.sprite.Sprite.__init__(self)
        self.text = name
        self.color = (0,0,0)
        self.font = pygame.font.Font(None,24)
        self.surface = self.font.render(name,1,self.color)
        self.image = self.surface
        self.rect = self.image.get_rect()
        self.rect.topleft = (700,y)
        textSprites.add(self)
class Error(pygame.sprite.Sprite):
    def __init__(self,text):
        pygame.sprite.Sprite.__init__(self)
        color = (250,0,0)
        self.font = pygame.font.Font(None,30)
        self.surface =self.font.render(text,1,color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.center = (1280/2,250 + len(messageSprites)*30)
        messageSprites.add(self)
        self.activated = True
        self.counter = 0
    def update(self):
        if self.activated == True:
            self.counter +=1
            if self.counter >= 80:
                messageSprites.clear(screen,backgroundSurface)
                self.kill()
                del self
                
class Buttons(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        buttonSprites.add(self)
        self.selected = False
class ResetButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("resetButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (700,620)
    def function(self):
        global deck
        global textSprites
        global textY
        deck = []
        textSprites.clear(screen,backgroundSurface)
        textSprites.empty()
        textY = 40
class SaveButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("saveButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (850,620)
    def function(self):
        global selected
        global inputSprites
        if selected != None:
            selected.unselect()
        txtLocX = self.rect.topleft[0]
        txtLocY = self.rect.topleft[1] -20
        txtbox = eztext.Input(x=txtLocX,y=txtLocY,color=(0,0,0),prompt=("What shall we name it?: "))
        inputSprites.add(txtbox)
        inputSprites.draw(screen)
        selected = self
        self.selected = True
    def update(self,events):
        global inputSprites
        if self.selected == True:
            for event in events:
                if event.type == KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        for sprite in inputSprites:
                            name = sprite.value
                        try:
                            saveDeck(name)
                            inputSprites.empty()
                            Error("Saved Successfully as " + name+ ".deck!")
                        except:
                            Error("Not a valid file name (.deck suffix automatically added)")
            inputSprites.update(events)
            inputSprites.clear(screen,backgroundSurface)
            inputSprites.draw(screen)
    def unselect(self):
        global selected
        self.selected = False
        selected = None
        inputSprites.clear(screen,backgroundSurface)
        inputSprites.empty()
class ExitButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("exitButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (1000,620)
    def function(self):
        global end
        end = True